<template>
  <div
    ref="editor"
    class="exercise-detail"
  >
    <h2 class="mb-4">
      {{ exercise.exerciseName }}
    </h2>
    <p class="mb-4 text-muted">
      总分：{{ exercise.totalScore }}分 | 题目数量：{{ exercise.questions.length }}道
    </p>

    <!-- 题目列表 -->
    <div
      v-for="(question, index) in exercise.questions"
      :key="question.id"
      class="mb-5"
    >
      <h4 class="mb-3 text-gray-700">
        题目 {{ index + 1 }}: {{ question.content }}
      </h4>

      <!-- 选择题 -->
      <div v-if="question.type === false">
        <div
          v-for="option in question.options"
          :key="option.key"
          class="form-check mb-3"
        >
          <input
            :id="'option-' + question.id + '-' + option.key"
            v-model="studentAnswers[question.id].selectedOptions"
            type="checkbox"
            class="form-check-input"
            :value="option.key"
          >
          <label 
            class="form-check-label"
            :for="'option-' + question.id + '-' + option.key"
          >
            {{ option.key }}. {{ option.text }}
          </label>
        </div>
      </div>

      <!-- 主观题 -->
      <div v-else>
        <textarea
          v-model="studentAnswers[question.id].textAnswer"
          class="form-control"
          rows="4"
          placeholder="请输入答案..."
        />
      </div>
    </div>

    <!-- 提交按钮 -->
    <div class="mt-8">
      <button
        class="btn btn-primary px-5 py-2"
        :disabled="!isFormFilled"
        @click="handleSubmit"
      >
        提交答案（共{{ exercise.questions.length }}题）
      </button>
    </div>
  </div>
</template>

<script>

export default {
  name: 'ExerciseDetail',
  props: {
    exercise: {
      type: Object,
      required: true
    }
  },
  emits: ['back', 'submit'],
  data() {
    return {
      studentAnswers: {}
    };
  },
  computed: {
    isFormFilled() {
      return Object.values(this.studentAnswers).every(answer => {
        return answer.selectedOptions.length > 0 || answer.textAnswer.trim() !== '';
      });
    }
  },
  created() {
    // 初始化答案对象
    this.exercise.questions.forEach(question => {
      this.studentAnswers[question.id] = {
        selectedOptions: [],
        textAnswer: ''
      };
    });
  },
  mounted() {
    // 在组件挂载后绑定事件到根元素
    this.editor = this.$refs.editor;
    this.editor.addEventListener('copy', this.handleCopy);
    this.editor.addEventListener('paste', this.handlePaste);
  },
  beforeUnmount() {
    // 组件卸载时移除事件监听器（避免内存泄漏）
    if (this.editor) {
      this.editor.removeEventListener('copy', this.handleCopy);
      this.editor.removeEventListener('paste', this.handlePaste);
    }
  },
  methods: {
    handleCopy(e) {
      // 阻止复制行为（可添加自定义提示）
      e.preventDefault();
      alert('禁止复制'); // 可选提示
    },
    handlePaste(e) {
      // 阻止粘贴行为（可添加自定义提示）
      e.preventDefault();
      alert('禁止粘贴'); // 可选提示
    },
    handleSubmit() {
      // 直接构造符合后端要求的答案结构
      const answers = this.exercise.questions.map(question => {
        return {
          id: {
            questionId: question.id,
            userId: this.$parent.userId, // 从父组件获取 userId
            exerciseId: this.exercise.exerciseId
          },
          studentAnswer: question.type === false 
            ? this.studentAnswers[question.id].selectedOptions.join('')
            : this.studentAnswers[question.id].textAnswer.trim(),
            gainScore: 0
        };
      });
      
      this.$emit('submit', answers);
    }
  }
};
</script>

<style scoped>
.exercise-detail {
  padding: 2rem;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  max-width: 800px;
  margin-left: 0; /* 左对齐 */
  margin-right: auto; /* 确保不会居中 */
  text-align: left;
}

h2 {
  font-weight: 600;
  color: #2d3748;
  padding-bottom: 0.5rem;
  border-bottom: 2px solid #e2e8f0;
  margin-bottom: 1.5rem;
}

.mb-4 {
  margin-bottom: 1.5rem;
}

.mb-3 {
  margin-bottom: 0.75rem;
}

.mb-5 {
  margin-bottom: 1.75rem;
}

.mt-5 {
  margin-top: 1.5rem;
}

.mt-8 {
  margin-top: 2.5rem;
}

.text-muted {
  color: #718096;
}

.form-check {
  padding-left: 1.5rem;
}

.form-check-input {
  margin-top: 0.3rem;
}

.form-control {
  border: 1px solid #e2e8f0;
  padding: 0.75rem;
  border-radius: 6px;
  transition: border-color 0.2s;
}

.form-control:focus {
  border-color: #4299e1;
  box-shadow: 0 0 0 2px rgba(66, 153, 225, 0.2);
}

.btn-primary {
  background-color: #4299e1;
  border-color: #4299e1;
  font-weight: 600;
  font-size: 1rem;
  transition: all 0.2s;
}

.btn-primary:hover {
  background-color: #3182ce;
  border-color: #3182ce;
  transform: translateY(-1px);
}

.btn-primary:disabled {
  background-color: #cbd5e0;
  border-color: #cbd5e0;
  opacity: 0.7;
  transform: none;
  cursor: not-allowed;
}

.form-check-label {
  cursor: pointer;
  color: #4a5568;
}

.text-gray-700 {
  color: #4a5568;
}

textarea {
  min-height: 120px;
  resize: vertical;
}
</style>